//
//  SpineTestViewModel.m
//  JiZhuiAn
//
//  Created by Easy.Lin on 16/6/20.
//  Copyright © 2016年 Easy. All rights reserved.
//

#import "SpineTestViewModel.h"

@implementation SpineTestViewModel

- (RACCommand *)submitCommand
{
    if (_submitCommand) {
        _submitCommand = [[RACCommand alloc]initWithEnabled:self.validSignal signalBlock:^RACSignal *(id input) {
            
            for(GWQuestionnaireItem *item in self.surveyItems)
            {
                NSLog(@"-----------------");
                NSLog(@"%@",item.question);
                NSLog(@"-----------------");
                if(item.type == GWQuestionnaireOpenQuestion)
                    NSLog(@"Answer: %@", item.userAnswer);
                else
                    for(NSDictionary *dict in item.answers)
                    {
                        NSLog(@"%d - %@",[[dict objectForKey:@"marked"]boolValue], [dict objectForKey:@"text"]);
                    }
                
            }
            return nil;
        }];
    }
    return _submitCommand;
}

- (RACSignal *)submitTheArray
{
    int testPoint = 0;
    for(int i = 0; i < [self.surveyItems count];i++)
    {
        GWQuestionnaireItem *item = [self.surveyItems objectAtIndex:i];

        testPoint += [self countThePointByItem:item];
    }
    if (testPoint >= 34) {
        injury = VERTEBRAINJURIESDISABILITY;
    }
    else if(testPoint >= 25){
        injury = VERTEBRAINJURIESHEAVY;
    }
    else if(testPoint >= 15){
        injury = VERTEBRAINJURIESMIDDLE;
    }
    else if(testPoint >= 5){
        injury = VERTEBRAINJURIESLIGHT;
    }
    else{
        injury = VERTEBRAINJURIESHEALTH;
    }
    
    int neckInjury;
    int waistInjury;
    if(self.testType == TESTTYPECERVICALVERTEBRA)
    {
        neckInjury  = (int)injury;
        waistInjury = 100;
    }
    else if(self.testType == TESTTYPELUMBARVERTEBRA)
    {
        neckInjury  = 100;
        waistInjury = (int)injury;
    }
    
    //提交到云平台
    return [[APIService shareService] submitSpineTestWithUserId:[APIService shareService].user.objectId NeckInjury:neckInjury waistInjury:waistInjury];
}

- (NSInteger)countThePointByItem:(GWQuestionnaireItem *)item
{
    int count = 0;
    for (int i = 1; i <= [item.answers count]; i++) {
        NSDictionary *dict = [item.answers objectAtIndex:(i - 1)];
        if ([[dict objectForKey:@"marked"]boolValue]) {
            count = i-1;
            break;
        }
    }
    return count;
}

- (RACSignal *)validSignal
{
    if (self.questionaireCompleted) {
        return @(1);
    }
    else
    {
        return @(0);
    }
}

@end
